//
//  NSDate+Ext.m
//  Pickers
//
//  Created by chaizhiyong on 14-7-30.
//
//

#import "NSDate+Ext.h"
@implementation NSDate (Ext)


+(NSInteger)currentMonthNum
{
    NSDateFormatter *formatter = [NSDateFormatter new];
    NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
    [formatter setLocale:usLocale];
    [formatter setDateFormat:@"M"];
    return [[formatter stringFromDate:[NSDate date]]integerValue];
}

+(NSInteger)currentYearNum
{
    NSDateFormatter *formatter = [NSDateFormatter new];
    [formatter setDateFormat:@"yyyy"];
    return [[formatter stringFromDate:[NSDate date]]integerValue];
}

+ (NSString *)stringYearMonthDayWithTimeStamp:(NSString*)timeStamp
{
    if(timeStamp == nil || timeStamp.length == 0){
        return [NSString string];
    }
    NSDate* date = [NSDate dateWithTimeIntervalSince1970:[timeStamp floatValue]];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *str = [formatter stringFromDate:date];
    return str;
}

+(NSString *)stringFullDateTimeStamp:(NSString*)timeStamp
{
    if(timeStamp == nil || timeStamp.length == 0){
        return [NSString string];
    }
    NSString *newTimeStamp = [NSString stringWithFormat:@"%lld",[timeStamp longLongValue]/1000];
    
    NSDate* date = [NSDate dateWithTimeIntervalSince1970:[newTimeStamp floatValue]];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    NSString *str = [formatter stringFromDate:date];
    return str;
}

+(NSString *)returnYearMonthDayWithTimeStamp:(NSString*)timeStamp{
    NSString *newTimeStamp = [NSString stringWithFormat:@"%lld",[timeStamp longLongValue]/1000];
    NSDate * nowDate = [NSDate date];
    NSDate* date = [NSDate dateWithTimeIntervalSince1970:[newTimeStamp floatValue]];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy"];
    NSString * yearStr = [dateFormatter stringFromDate:date];
    NSString *nowYear = [dateFormatter stringFromDate:nowDate];
    NSString *str = [[NSString alloc] init];
    if ([yearStr isEqualToString:nowYear]) {
        ////  在同一年
        [dateFormatter setDateFormat:@"MM月dd日"];
        str = [dateFormatter stringFromDate:date];
    }else{
        [dateFormatter setDateFormat:@"yyyy年-MM月-dd日"];
        str = [dateFormatter stringFromDate:date];
    }
    return str;
}

+ (NSString*)getHourWithTimeStamp:(NSString*)timeStamp
{
    if(timeStamp == nil || timeStamp.length == 0){
        return [NSString string];
    }
    NSDate* date = [NSDate dateWithTimeIntervalSince1970:[timeStamp floatValue]];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:@"HH:mm"];
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [dateFormatter setTimeZone:timeZone];
    //用[NSDate date]可以获取系统当前时间
    return [dateFormatter stringFromDate:date];
}

//是当天返回 返回 12：00 格式 昨天的 返回 昨天  其他的返回 10/20

+ (NSString*)getGregorianCalendarWithTimeStamp:(NSString*)timeStamp
{
    if(timeStamp == nil || timeStamp.length == 0){
        return [NSString string];
    }
    NSDate* date = [NSDate dateWithTimeIntervalSince1970:[timeStamp floatValue]];
    NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];//实例化一个NSDateFormatter对象
    NSTimeInterval secondsPerDay = 24 * 60 * 60;
    NSDate *today = [NSDate date];
    NSDate *yesterday;
    
    yesterday = [today dateByAddingTimeInterval: -secondsPerDay];
    
    NSString * todayString = [[today description] substringToIndex:10];
    NSString * yesterdayString = [[yesterday description] substringToIndex:10];
    NSString * dateString = [[date description] substringToIndex:10];
    
    if ([dateString isEqualToString:todayString]){
        [dateFormat setDateFormat:@"HH:mm"];//设定时间格式
        NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
        [dateFormat setTimeZone:timeZone];
        NSString *dateString = [dateFormat stringFromDate:date];
        return dateString;
    } else if ([dateString isEqualToString:yesterdayString]){
        return @"昨天";
    }else{
        [dateFormat setDateFormat:@"MM/dd"];//设定时间格式
        NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
        [dateFormat setTimeZone:timeZone];
        NSString *dateString = [dateFormat stringFromDate:date];
        return dateString;
    }
    return [NSString string];
}

//是 当天返回---今天12：00格式, 昨天的返回--昨天+时间格式 , 其他的返回 10/20+时间
+ (NSString*)getGregorianCalendarAndTimeWithTimeStamp:(NSDate*)Datetime{
    if (Datetime == nil) {
        return [NSString string];
    }
    NSTimeInterval secondsPerDay = 24 * 60 * 60;
    NSDate *today = [NSDate date];
    NSDate *tomorrow, *yesterday;
    tomorrow = [today dateByAddingTimeInterval: secondsPerDay];
    yesterday = [today dateByAddingTimeInterval: -secondsPerDay];
    // 10 first characters of description is the calendar date:
    NSString * todayString = [[today description] substringToIndex:10];
    NSString * yesterdayString = [[yesterday description] substringToIndex:10];
    NSString * tomorrowString = [[tomorrow description] substringToIndex:10];
    NSString * dateString = [[Datetime description] substringToIndex:10];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"HH:mm"];//设定时间格式
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [dateFormatter setTimeZone:timeZone];
    NSString *time = [dateFormatter stringFromDate:Datetime];
    if ([dateString isEqualToString:todayString]){
        return [NSString stringWithFormat:@"今天 %@",time];
    } else if ([dateString isEqualToString:yesterdayString]){
        return [NSString stringWithFormat:@"昨天 %@",time];
    }else if ([dateString isEqualToString:tomorrowString]){
        NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];//设置成中国阳历
        NSDateComponents *components = [calendar components: NSCalendarUnitHour|NSCalendarUnitMinute  fromDate:Datetime];
        NSInteger month = [components month];
        NSInteger day = [components day];
        return [NSString stringWithFormat:@"%ld/%ld %@",month,day,time];
    }else{
        return dateString;
    }
}
/*
 * 粉丝列表时间、好评列表时间、咨询列表时间、
 * 0-60s              刚刚
 * 60s-1小时        x分钟前
 * 1小时-24小时      x小时前
 * 1天-30天           x天前
 * 1个月-12个月        x月前
 * 大于1年             x年前
 */
- (NSString *)formateCurrentDate{
    NSDate * nowDate = [NSDate date];
    NSTimeZone* zone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    NSInteger interval = [zone secondsFromGMTForDate: nowDate];
    NSDate *localeDate = [nowDate  dateByAddingTimeInterval: interval];
    NSTimeInterval time = [localeDate timeIntervalSinceDate:self];
    NSString *dateStr = @"";
    if (time <=60) {
        dateStr = @"刚刚";
    }else if(time<=60*60){
        int min = time/60;
        dateStr = [NSString stringWithFormat:@"%d分钟前",min];
    }else if(time<=60*60*24){
        int hour = time/(60*60);
        dateStr = [NSString stringWithFormat:@"%d小时前",hour];
    }else if(time<=60*60*24*30){
        int day = roundf(time/(60.0*60.0*24.0));
        dateStr = [NSString stringWithFormat:@"%d天前",day];
    }else if(time<=60*60*24*30*12){
        int mouth = time/(60*60*24*30);
        dateStr = [NSString stringWithFormat:@"%d月前",mouth];
    }else if(time>60*60*24*30*12){
        int year = time/(60*60*24*30*12);
        dateStr = [NSString stringWithFormat:@"%d年前",year];
    }
    return dateStr;
}
/*
 * 咨询对话框
 * 消息2分钟内                    无显示
 * 2分钟-24小时                   13:12
 * 昨天                      昨天 13:12
 *前天                       前天 13:12
 *一年之内                 9月12日 13:12
 *去年                去年 9月12日 13:12
 *前年                前年 9月12日 13:12
 *比前年更早的时间     2012年9月12日 13:12
 */
- (NSString *)formateChatCurrentDateFromMe{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"HH:mm"];
    return [dateFormatter stringFromDate:self];
}
- (NSString *)formateChatCurrentDate{
    NSDate * nowDate = [NSDate date];
    NSTimeInterval time = [nowDate timeIntervalSinceDate:self];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    NSString *dateStr = @"";
    if (time <=60*2) {
        
    }else if(time<=60*60*24){
        [dateFormatter setDateFormat:@"HH:mm"];
        dateStr = [dateFormatter stringFromDate:self];
    }else if(time<=60*60*24*3){
        [dateFormatter setDateFormat:@"HH:mm"];
        dateStr = [NSString stringWithFormat:@"%@ %@",[self timeIntervalForZN],[dateFormatter stringFromDate:self]];
    }else if(time<=60*60*24*30*12){
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"MM月dd日 HH:mm"];
         dateStr = [dateFormatter stringFromDate:self];
    }else if(time>60*60*24*30*12){
        
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"MM月dd日 HH:mm"];
        
        NSCalendar* calendar = [NSCalendar currentCalendar];
        NSDateComponents* nowComponents = [calendar components:NSCalendarUnitYear fromDate:nowDate];
        NSDateComponents* oldComponents = [calendar components:NSCalendarUnitYear fromDate:self];
        NSInteger yearInterval = nowComponents.year - oldComponents.year;
        if(1 == yearInterval){
            dateStr = [NSString stringWithFormat:@"去年 %@",[dateFormatter stringFromDate:self]];
        }else if(2 == yearInterval){
            dateStr = [NSString stringWithFormat:@"前年 %@",[dateFormatter stringFromDate:self]];
        }else{
            [dateFormatter setDateFormat:@"yyyy年MM月dd日 HH:mm"];
             dateStr = [NSString stringWithFormat:@"%@",[dateFormatter stringFromDate:self]];
        }
    }
    return dateStr;
}

/**
 /////  和当前时间比较
 ////   1）1分钟以内 显示        :    刚刚
 ////   2）1小时以内 显示        :    X分钟前
 ///    3）今天或者昨天 显示      :    今天 09:30   昨天 09:30
 ///    4) 今年显示              :   09月12日
 ///    5) 大于本年      显示    :    2013/09/09
 **/
+ (NSString *)formateDate:(NSString *)dateString withFormate:(NSString *) formate
{
    
    @try {
        //实例化一个NSDateFormatter对象
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:formate];
        
        NSDate * nowDate = [NSDate date];
        
        /////  将需要转换的时间转换成 NSDate 对象
        NSDate * needFormatDate = [dateFormatter dateFromString:dateString];
        /////  取当前时间和转换时间两个日期对象的时间间隔
        /////  这里的NSTimeInterval 并不是对象，是基本型，其实是double类型，是由c定义的:  typedef double NSTimeInterval;
        NSTimeInterval time = [nowDate timeIntervalSinceDate:needFormatDate];
        
        //// 再然后，把间隔的秒数折算成天数和小时数：
        
        NSString *dateStr = @"";
        
        if (time<=60) {  //// 1分钟以内的
            dateStr = @"刚刚";
        }else if(time<=60*60){  ////  一个小时以内的
            
            int mins = time/60;
            dateStr = [NSString stringWithFormat:@"%d分钟前",mins];
            
        }else if(time<=60*60*24){   //// 在两天内的
            
            [dateFormatter setDateFormat:@"YYYY/MM/dd"];
            NSString * need_yMd = [dateFormatter stringFromDate:needFormatDate];
            NSString *now_yMd = [dateFormatter stringFromDate:nowDate];
            
            [dateFormatter setDateFormat:@"HH:mm"];
            if ([need_yMd isEqualToString:now_yMd]) {
                //// 在同一天
                dateStr = [NSString stringWithFormat:@"今天 %@",[dateFormatter stringFromDate:needFormatDate]];
            }else{
                ////  昨天
                dateStr = [NSString stringWithFormat:@"昨天 %@",[dateFormatter stringFromDate:needFormatDate]];
            }
        }else {
            
            [dateFormatter setDateFormat:@"yyyy"];
            NSString * yearStr = [dateFormatter stringFromDate:needFormatDate];
            NSString *nowYear = [dateFormatter stringFromDate:nowDate];
            
            if ([yearStr isEqualToString:nowYear]) {
                ////  在同一年
                [dateFormatter setDateFormat:@"MM月dd日"];
                dateStr = [dateFormatter stringFromDate:needFormatDate];
            }else{
                [dateFormatter setDateFormat:@"yyyy/MM/dd"];
                dateStr = [dateFormatter stringFromDate:needFormatDate];
            }
        }
        return dateStr;
    }
    @catch (NSException *exception) {
        return @"";
    }
}

/**
 /////  和当前时间比较
 ///    3）今天或者昨天 显示      :    今天 09:30   昨天 09:30
 ///    4) 今年显示              :   09月12日
 ///    5) 大于本年      显示    :    2013/09/09
 **/
+ (NSString *)formateDateNew:(NSString *)dateString withFormate:(NSString *) formate
{
    
    @try {
        //实例化一个NSDateFormatter对象
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:formate];
        
        NSDate * nowDate = [NSDate date];
        
        /////  将需要转换的时间转换成 NSDate 对象
        NSDate * needFormatDate = [dateFormatter dateFromString:dateString];
        /////  取当前时间和转换时间两个日期对象的时间间隔
        /////  这里的NSTimeInterval 并不是对象，是基本型，其实是double类型，是由c定义的:  typedef double NSTimeInterval;
        NSTimeInterval time = [nowDate timeIntervalSinceDate:needFormatDate];
        
        //// 再然后，把间隔的秒数折算成天数和小时数：
        
        NSString *dateStr = @"";
        
//        if (time<=60) {  //// 1分钟以内的
//            dateStr = @"刚刚";
//        }else if(time<=60*60){  ////  一个小时以内的
//            
//            int mins = time/60;
//            dateStr = [NSString stringWithFormat:@"%d分钟前",mins];
//            
//        }else
        
        if(time<=60*60*24){   //// 在两天内的
        
            [dateFormatter setDateFormat:@"YYYY/MM/dd"];
            NSString * need_yMd = [dateFormatter stringFromDate:needFormatDate];
            NSString *now_yMd = [dateFormatter stringFromDate:nowDate];
            
            [dateFormatter setDateFormat:@"HH:mm"];
            if ([need_yMd isEqualToString:now_yMd]) {
                //// 在同一天
                dateStr = [NSString stringWithFormat:@"今天 %@",[dateFormatter stringFromDate:needFormatDate]];
            }else{
                ////  昨天
                dateStr = [NSString stringWithFormat:@"昨天 %@",[dateFormatter stringFromDate:needFormatDate]];
            }
        }else {
            
            [dateFormatter setDateFormat:@"yyyy"];
            NSString * yearStr = [dateFormatter stringFromDate:needFormatDate];
            NSString *nowYear = [dateFormatter stringFromDate:nowDate];
            
            if ([yearStr isEqualToString:nowYear]) {
                ////  在同一年
                [dateFormatter setDateFormat:@"MM月dd日"];
                dateStr = [dateFormatter stringFromDate:needFormatDate];
            }else{
                [dateFormatter setDateFormat:@"yyyy/MM/dd"];
                dateStr = [dateFormatter stringFromDate:needFormatDate];
            }
        }
        
        return dateStr;
    }
    @catch (NSException *exception) {
        return @"";
    }
}

+ (NSString *)formateDateWithDate:(NSDate *)date{
    //实例化一个NSDateFormatter对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSDate * nowDate = [NSDate date];
    
    /////  将需要转换的时间转换成 NSDate 对象
    NSDate * needFormatDate = date;
    /////  取当前时间和转换时间两个日期对象的时间间隔
    /////  这里的NSTimeInterval 并不是对象，是基本型，其实是double类型，是由c定义的:  typedef double NSTimeInterval;
    NSTimeInterval time = [nowDate timeIntervalSinceDate:needFormatDate];
    
    //// 再然后，把间隔的秒数折算成天数和小时数：
    
    NSString *dateStr = @"";
    
    //        if (time<=60) {  //// 1分钟以内的
    //            dateStr = @"刚刚";
    //        }else if(time<=60*60){  ////  一个小时以内的
    //
    //            int mins = time/60;
    //            dateStr = [NSString stringWithFormat:@"%d分钟前",mins];
    //
    //        }else
    
    if(time<=60*60*24){   //// 在两天内的
        
        [dateFormatter setDateFormat:@"YYYY/MM/dd"];
        NSString * need_yMd = [dateFormatter stringFromDate:needFormatDate];
        NSString *now_yMd = [dateFormatter stringFromDate:nowDate];
        
        [dateFormatter setDateFormat:@"HH:mm"];
        if ([need_yMd isEqualToString:now_yMd]) {
            //// 在同一天
            dateStr = [NSString stringWithFormat:@"今天 %@",[dateFormatter stringFromDate:needFormatDate]];
        }else{
            ////  昨天
            dateStr = [NSString stringWithFormat:@"昨天 %@",[dateFormatter stringFromDate:needFormatDate]];
        }
    }else {
        
        [dateFormatter setDateFormat:@"yyyy"];
        NSString * yearStr = [dateFormatter stringFromDate:needFormatDate];
        NSString *nowYear = [dateFormatter stringFromDate:nowDate];
        
        if ([yearStr isEqualToString:nowYear]) {
            ////  在同一年
            [dateFormatter setDateFormat:@"MM-dd HH:mm"];
            dateStr = [dateFormatter stringFromDate:needFormatDate];
        }else{
            [dateFormatter setDateFormat:@"yyyy/MM/dd"];
            dateStr = [dateFormatter stringFromDate:needFormatDate];
        }
    }
    
    return dateStr;
}

+ (NSString* )formatMonthWithDate:(NSDate *)date{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"MM/dd"];
    NSDate * needFormatDate = date;
    return  [dateFormatter stringFromDate:needFormatDate];
}

+ (NSString* )formatYear_MonthWithDate:(NSDate *)date{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM"];
    NSDate * needFormatDate = date;
    return  [dateFormatter stringFromDate:needFormatDate];
}

+ (NSString* )formatYear_Month_Day_WithDate:(NSDate *)date{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSDate * needFormatDate = date;
    return  [dateFormatter stringFromDate:needFormatDate];
}

-(NSString *)timeIntervalForZN
{

    NSTimeInterval secondsPerDay = 24 * 60 * 60;
    NSDate *today = [NSDate date];
    NSDate *tomorrow, *yesterday,*before_yesterday;
    
    tomorrow = [today dateByAddingTimeInterval: secondsPerDay];
    yesterday = [today dateByAddingTimeInterval: -secondsPerDay];
    before_yesterday = [today dateByAddingTimeInterval: -secondsPerDay*2];
    // 10 first characters of description is the calendar date:
    NSString * todayString = [[today description] substringToIndex:10];
    NSString * yesterdayString = [[yesterday description] substringToIndex:10];
    NSString * before_yesterdayString = [[before_yesterday description] substringToIndex:10];
    NSString * tomorrowString = [[tomorrow description] substringToIndex:10];
    
    NSString * dateString = [[self description] substringToIndex:10];
    if ([dateString isEqualToString:todayString]){
        return @"今天";
    } else if ([dateString isEqualToString:yesterdayString]){
        return @"昨天";
    }else if ([dateString isEqualToString:before_yesterdayString]){
        return @"前天";
    }else if ([dateString isEqualToString:tomorrowString]){
        return @"明天";
    }else{
        return dateString;
    }
}

+ (NSString *)speCompareCurDate
{
     NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
     NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [dateFormatter setTimeZone:timeZone];
    //用[NSDate date]可以获取系统当前时间
     return [dateFormatter stringFromDate:[NSDate date]];
}

+(NSString*)coverDateFormatterWithDate:(NSDate*)date
{
  NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  [formatter setDateStyle:NSDateFormatterMediumStyle];
  [formatter setTimeStyle:NSDateFormatterShortStyle];
  [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
  NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
  [formatter setTimeZone:timeZone];
  return [formatter stringFromDate:date];
}

+ (NSString *)coveDateUserYearMountDayWithDate:(NSDate *)date{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"YYYY-MM-dd"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [formatter setTimeZone:timeZone];
    return [formatter stringFromDate:date];
}

//2014-10-5 12:00:00 转成date
+(NSDate*)coverDateWithFormatter:(NSString*)time
{
    return [self coverDateWithFormatter:time format:nil];
}


+(NSDate *)coverDateWithFormatter:(NSString *)time format:(NSString *)format
{
    if (time == nil || time.length == 0) {
        return nil;
    }
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    if([NSString blIsBlankString:format]) format = @"YYYY-MM-dd HH:mm:ss";
    [formatter setDateFormat:format]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [formatter setTimeZone:timeZone];
    return [formatter dateFromString:time];
}

+ (BOOL)isBetweenFromTime:(NSDate*)fromTime toTime:(NSDate*)toTime
{
    if (fromTime == nil || toTime == nil) {
        return NO;
    }
    
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];//设置成中国阳历
    NSDateComponents *components_start = [calendar components: NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear | NSCalendarUnitHour|NSCalendarUnitMinute  fromDate:fromTime];
   
    NSInteger hour_start = [components_start hour];
    NSInteger minute_start = [components_start minute];
    
    NSDateComponents *components_end= [calendar components: NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear | NSCalendarUnitHour|NSCalendarUnitMinute  fromDate:toTime];
    
    NSInteger hour_end = [components_end hour];
    NSInteger minute_end = [components_end minute];
    
    NSDate *date_start = [self getCustomDateWithHour:hour_start minute:minute_start];
    NSDate *date_end = [self getCustomDateWithHour:hour_end minute:minute_end];
    
    NSDate *currentDate = [NSDate date];
    
    if ([currentDate compare:date_start]==NSOrderedDescending && [currentDate compare:date_end]==NSOrderedAscending){
        return YES;
    }
    return NO;
}

+ (BOOL)isBetweenFromHour:(NSInteger)fromHour toHour:(NSInteger)toHour
{
    NSDate *date_start = [self getCustomDateWithHour:fromHour minute:0];
    NSDate *date_end = [self getCustomDateWithHour:toHour minute:0];
    
    NSDate *currentDate = [NSDate date];
    
    if ([currentDate compare:date_start]==NSOrderedDescending && [currentDate compare:date_end]==NSOrderedAscending){
        return YES;
    }
    return NO;
}
/**
 * @brief 生成当天的某个点（返回的是伦敦时间，可直接与当前时间[NSDate date]比较）
 * @param hour 如hour为“8”，就是上午8:00（本地时间）
 */
+ (NSDate *)getCustomDateWithHour:(NSInteger)hour minute:(NSInteger)minute
{
    //获取当前时间
    NSDate *currentDate = [NSDate date];
    NSCalendar *currentCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *currentComps = [[NSDateComponents alloc] init];
    
    NSInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekday | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    
    currentComps = [currentCalendar components:unitFlags fromDate:currentDate];
    //设置当天的某个点
    NSDateComponents *resultComps = [[NSDateComponents alloc] init];
    [resultComps setYear:[currentComps year]];
    [resultComps setMonth:[currentComps month]];
    [resultComps setDay:[currentComps day]];
    [resultComps setHour:hour];
    [resultComps setMinute:minute];
    NSCalendar *resultCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    return [resultCalendar dateFromComponents:resultComps];
}

- (NSString*)getTimestamp
{
    NSTimeInterval a=[self timeIntervalSince1970]*1000;
    return [NSString stringWithFormat:@"%.0f", a];
}

+ (NSDate *)getDateWithTimeStamp:(NSString*)timeStamp
{
    if(timeStamp ==nil && timeStamp.length == 0){
        return nil;
    }
    NSDate* date = [NSDate dateWithTimeIntervalSince1970:[timeStamp longLongValue]/1000];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate: date];
    NSDate *localeDate = [date  dateByAddingTimeInterval: interval];
    return localeDate;
}
//传入时间戳 返回格式 上午 8:00
+ (NSString*)getGregorianWithTimeStamp:(NSString *)timeStamp
{
    if (timeStamp == nil || timeStamp.length == 0) {
        return [NSString string];
    }
    NSDate* date = [NSDate getDateWithTimeStamp:timeStamp];
    NSString* time = [NSDate getGregorianWithdate:date];
    return time;
}
// 传入时间戳 返回格式 上午 8:00 上边那个方法会在时间戳+16小时，这个是+8小时
+ (NSString*)getNormalWithTimeStamp:(NSString *)timeStamp{
    if (timeStamp == nil || timeStamp.length == 0) {
        return [NSString string];
    }
    NSDate* date = [NSDate dateWithTimeIntervalSince1970:[timeStamp longLongValue]/1000];
    NSString* time = [NSDate getGregorianWithdate:date];
    return time;
}

//传入NSDate 返回格式 上午 8:00
+ (NSString*)getGregorianWithdate:(NSDate *)date
{
    if (date == nil) {
        return [NSString string];
    }
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];//设置成中国阳历
    NSDateComponents *components = [calendar components: NSCalendarUnitHour|NSCalendarUnitMinute  fromDate:date];
    
    NSInteger hour = [components hour];
    NSInteger minute = [components minute];
    
    NSString* AMPM = (hour - 12) > 0 ? @"下午":@"上午";
    hour = (hour - 12) > 0 ? (hour - 12):hour;
    NSString* time = [NSString stringWithFormat:@"%@ %02d:%02d",AMPM, (int)hour,(int)minute];
    return time;
}

#pragma mark ---- 返回聊天结束时间格式
+ (NSDate *)returnDateByTimer:(NSString *)timerString{
    NSDate *detaildate=[NSDate dateWithTimeIntervalSince1970:timerString.doubleValue/1000];
    return detaildate;
}

+ (BOOL)date:(NSDate*)date isBetweenDate:(NSDate*)beginDate andDate:(NSDate*)endDate
{
    if ([date compare:beginDate] == NSOrderedAscending)
        return NO;
    
    if ([date compare:endDate] == NSOrderedDescending)
        return NO;
    
    return YES;
}

+ (BOOL)timestamp:(NSString*)dateStr isBetweenDate:(NSString*)beginDateStr andDate:(NSString*)endDateStr
{
    if ([NSString blIsBlankString:dateStr]) {
        return NO;
    }
    NSDate* date = [NSDate getDateWithTimeStamp:dateStr];
    NSDate* beginDate = [NSDate getDateWithTimeStamp:beginDateStr];
    NSDate* endDate = [NSDate getDateWithTimeStamp:endDateStr];
    return  [NSDate date:date isBetweenDate:beginDate andDate:endDate];
}

#pragma mark --- 返回距离当前时间的日期
+ (NSString *)returnDateFromNow:(NSInteger)days{
    NSDate*nowDate = [NSDate date];
    NSDate* theDate;
    NSTimeInterval  oneDay = 24*60*60*1;  //1天的长度
    //之后的天数
    theDate = [nowDate initWithTimeIntervalSinceNow: +oneDay*days ];
    //实例化一个NSDateFormatter对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:@"yyyy年MM月dd日"];
    //用[NSDate date]可以获取系统当前时间
    NSString * currentDateStr = [dateFormatter stringFromDate:theDate];
    return currentDateStr;
}

+ (NSString *)timeFormatted:(int)totalSeconds{
    int h,m,s;
    h = (totalSeconds/60)/60;
    m = (totalSeconds / 60) % 60;
    s = totalSeconds%60;
    return [NSString stringWithFormat:@"%02d:%02d:%02d",h, m, s];
}

+ (NSString *)intervalFromLastDate:(NSDate *)startDate toTheDate:(NSDate *) endDate
{
    NSTimeInterval start = [startDate timeIntervalSince1970]*1;
    NSTimeInterval end = [endDate timeIntervalSince1970]*1;
    NSTimeInterval cha = end - start;
    NSMutableString* timeString = [NSMutableString string];
    if ((int)cha/3600 > 0) {
      [timeString appendFormat:@"%d小时",(int)cha/3600];
    }
    
    int min = (int)cha%3600;
    if(min > 0){
      [timeString appendFormat:@"%d分",(int)min/60];
    }
    
    int sen = (int)cha%3600%60;
    if(sen > 0){
      [timeString appendFormat:@"%d秒",(int)sen];
    }
    return timeString;
}
+ (NSString *)intervalFromTimeInterval:(long long)timeInterval
{
    NSMutableString* timeString = [NSMutableString string];
    if (timeInterval == 0) {
       [timeString appendFormat:@"0秒"];
    }
    NSTimeInterval cha = timeInterval;
  
    if ((int)cha/3600 > 0) {
      [timeString appendFormat:@"%d小时",(int)cha/3600];
    }
    
    int min = (int)cha%3600;
    if(min > 0){
      [timeString appendFormat:@"%d分",(int)min/60];
    }
    
    int sen = (int)cha%3600%60;
    if(sen > 0){
      [timeString appendFormat:@"%d秒",(int)sen];
    }
    return timeString;
}

+ (NSString *)currentDate {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    return [formatter stringFromDate:[NSDate date]];
}

+(NSString*)convertDateToDateString:(NSDate*)date andDateFormat:(NSString*)dateFormat{
    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:dateFormat];
    return [dateFormatter stringFromDate:date];
}

+(NSDate*)convertDateStringToDate:(NSString*)dateString andDateFormat:(NSString*)dateFormat{
    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:dateFormat];
    return [dateFormatter dateFromString:dateString];
}

+(NSInteger)firstWeekdayInThisMonth:(NSDate*)date{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    //设置每周的第一天从周几开始,默认为1,从周日开始   1.Sun. 2.Mon. 3.Thes. 4.Wed. 5.Thur. 6.Fri. 7.Sat.
    [calendar setFirstWeekday:1];
    NSDateComponents *comp = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:date];
    [comp setDay:1];
    NSDate *firstDayOfMonthDate = [calendar dateFromComponents:comp];
    NSUInteger firstWeekday = [calendar ordinalityOfUnit:NSCalendarUnitWeekday inUnit:NSCalendarUnitWeekOfMonth forDate:firstDayOfMonthDate];
    //若设置从周日开始算起则需要减一,若从周一开始算起则不需要减
    return firstWeekday - 1;
}

+(NSDate*)getFirstDayofThisMonthWithDate:(NSDate*)date{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *comp = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:date];
    [comp setDay:1];
    NSDate *firstDayOfMonthDate = [calendar dateFromComponents:comp];
    return firstDayOfMonthDate;
}

+(NSDate*)getLastDayOfThisMonthWithDate:(NSDate*)date andDateFormat:(NSString*)dateFormat{
    //获取下个月对应的日期
    NSString* nextMonthDate = [self getDestinationDateFromDate:[self convertDateToDateString:date andDateFormat:dateFormat] andMonth:1 andDateFormat:dateFormat];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *comp = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:[self convertDateStringToDate:nextMonthDate andDateFormat:dateFormat]];
    //获取下个月第一天日期
    [comp setDay:1];
    NSDate* nextFirstDate = [calendar dateFromComponents:comp];
    //获取当月最后一天日期
    NSDateComponents* addComps = [[NSDateComponents alloc]init];
    [addComps setDay:-1];
    
    return [calendar dateByAddingComponents:addComps toDate:nextFirstDate options:0];
}

+(NSInteger)weekdayOfDestinationDate:(NSDate*)date{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    [calendar setFirstWeekday:1];
    NSUInteger weekday = [calendar ordinalityOfUnit:NSCalendarUnitWeekday inUnit:NSCalendarUnitWeekOfMonth forDate:date];
    return weekday - 1;
}

+(NSInteger)totaldaysInThisMonth:(NSDate *)date{
    NSRange daysInLastMonth = [[NSCalendar currentCalendar] rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:date];
    return daysInLastMonth.length;
}

+(NSComparisonResult)compareDateWithOneDate:(NSString *)oneDateStr andTwoDate:(NSString *)TwoDateStr andDateFormat:(NSString*)dateFormat{
    NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:dateFormat];
    NSDate* oneDate = [formatter dateFromString:oneDateStr];
    NSDate* twoDate = [formatter dateFromString:TwoDateStr];
    NSComparisonResult result = [oneDate compare:twoDate];
    
    return result;
}

+(NSArray<NSString*>*)getMaxDateAndMinDateWithDateArr:(NSArray<NSString*>*)dateArr andDateFormat:(NSString *)dateFormat{
    NSString* maxDateStr = nil;
    NSString* minDateStr = nil;
    
    for (NSString* dateStr in dateArr) {
        if (!minDateStr || [self compareDateWithOneDate:minDateStr andTwoDate:dateStr andDateFormat:dateFormat] == NSOrderedDescending) {
            minDateStr = dateStr;
        }
        if (!maxDateStr || [self compareDateWithOneDate:maxDateStr andTwoDate:dateStr andDateFormat:dateFormat] == NSOrderedAscending) {
            maxDateStr = dateStr;
        }
    }
    if (![NSString blIsBlankString:minDateStr] && ![NSString blIsBlankString:maxDateStr]) {
        return @[minDateStr, maxDateStr];
    }else{
        minDateStr = [self formatYear_Month_Day_WithDate:[NSDate date]];
        maxDateStr = [self formatYear_Month_Day_WithDate:[NSDate date]];
        return @[minDateStr, maxDateStr];
    }
}

+(NSInteger)computeMonthsWithStartDate:(NSString *)startDateStr andEndDate:(NSString *)endDateStr andDateFormat:(NSString *)dateFormat{
//    //此方法为计算包括天数的算法
//    NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
//    [formatter setDateFormat:dateFormat];
//    NSDate* startDate = [formatter dateFromString:startDateStr];
//    NSDate* endDate = [formatter dateFromString:endDateStr];
//
//    NSDateComponents* delta = [[NSCalendar currentCalendar] components:NSCalendarUnitMonth fromDate:startDate toDate:endDate options:0];
//    return delta.month;
    
    //此方法为只计算到月份，不考虑天数
    NSDate* startDate = [self convertDateStringToDate:startDateStr andDateFormat:dateFormat];
    NSDate* endDate = [self convertDateStringToDate:endDateStr andDateFormat:dateFormat];
    NSDateComponents* startComps = [[NSCalendar currentCalendar] components:NSCalendarUnitYear|NSCalendarUnitMonth fromDate:startDate];
    NSDateComponents* endComps = [[NSCalendar currentCalendar] components:NSCalendarUnitYear|NSCalendarUnitMonth fromDate:endDate];
    
    return (endComps.year*12+endComps.month)-(startComps.year*12+startComps.month);
}

+(NSString*)getDestinationDateFromDate:(NSString*)dateStr andMonth:(NSInteger)month andDateFormat:(NSString *)dateFormat{
    NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:dateFormat];
    NSDate* date = [formatter dateFromString:dateStr];
    
    NSDateComponents* comps = [[NSDateComponents alloc]init];
    [comps setMonth:month];
    NSDate* destinationDate = [[NSCalendar currentCalendar] dateByAddingComponents:comps toDate:date options:0];

    return [self convertDateToDateString:destinationDate andDateFormat:dateFormat];
}

+(NSArray<NSString*>*)filterSameMonthDateWithDateArr:(NSArray<NSString*>*)dateArr andDestinationDate:(NSString*)destinationDateStr andDateFormat:(NSString *)dateFormat{
    NSMutableArray* destArr = [NSMutableArray array];
    
    NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:dateFormat];
    NSDate* destDate = [formatter dateFromString:destinationDateStr];
    NSDateComponents* destComps = [[NSCalendar currentCalendar] components:NSCalendarUnitYear|NSCalendarUnitMonth fromDate:destDate];

    for (NSString* dateStr in dateArr) {
        NSDate* date = [formatter dateFromString:dateStr];
        NSDateComponents* dateComps = [[NSCalendar currentCalendar] components:NSCalendarUnitYear|NSCalendarUnitMonth fromDate:date];
        if (destComps.year == dateComps.year && destComps.month == dateComps.month) {
            [destArr addObject:dateStr];
        }
    }
    
    return [destArr copy];
}

+ (NSString *)computeDateWithDays:(NSInteger)days fromDateString:(NSString *)date{
   
    NSDateFormatter *dateFormatter = [NSDateFormatter new];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSDate *myDate = [dateFormatter dateFromString:date];
    NSDate *newDate = [myDate dateByAddingTimeInterval:60 * 60 * 24 * days];
    return [dateFormatter stringFromDate:newDate];
}

#pragma mark --- 计算一个月后的日期
+(NSDate *)getPriousorLaterDateFromDate:(NSDate *)date withMonth:(NSInteger)month
{
  NSDateComponents *comps = [[NSDateComponents alloc] init];
  [comps setMonth:month];
  NSCalendar *calender = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
  NSDate *mDate = [calender dateByAddingComponents:comps toDate:date options:0];
  return mDate;
}
@end
